package cc.rengu.igas.share.common.util;

import cc.rengu.igas.share.common.constant.ShareParamConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.dao.CertInfoMapper;
import cc.rengu.oltp.service.common.dao.SecPlanInfoMapper;
import cc.rengu.oltp.service.common.dao.SrcChannelInfoMapper;
import cc.rengu.oltp.service.common.dao.impl.CertInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SecPlanInfoMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SrcChannelInfoMapperImpl;
import cc.rengu.oltp.service.common.entity.CertInfo;
import cc.rengu.oltp.service.common.entity.SecPlanInfo;
import cc.rengu.oltp.service.common.entity.SrcChannelInfo;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.utility.util.StringUtil;

import java.security.PrivateKey;

public class OpenEncyOrDecryptUtil {
    /**
     * 使用客户端密钥进行解密
     *
     * @param reqId
     * @param jsonData
     * @return
     */
    public static String decryptByClusterKey(String bankId, String jsonData, String srcMsgId, String reqId) throws Exception {
        String key = ShareParamConstant.EBUS_CER_MSG;
        //拆分jsonData
        String algorFlag = jsonData.substring(0, 1);
        //判断algorFlag是否为3，若为3使用证书1；其他使用证书0；
        if ("3".equals(algorFlag)) {
            key = ShareParamConstant.EBUS_CER_MSG_APP;
            /*新算法证书*/
            reqId += "NM";
        } else {
            /*老算法证书*/
            reqId += "OM";
        }
        //RSACerPlus rsaCerPlus = RSACerFactory.getInstance().init(key, "F:\\NEWWORKSPACE\\igas\\igas-release\\cfg\\cert\\", "ERxRC97D5PdYhm9ngrqHvsF8OemxxmAE3BI8XAgARF3wjzSvykMVYybMFsTvt7SZ6U5aEpsAHfOR5/P3Qe0pdEMhs8gZ+XNu");
        RSACerPlus rsaCerPlus = genRSACerPlus(bankId, reqId, key, srcMsgId);
        //获取加密字符串长度
        String keyLen = jsonData.substring(1, 4);

        //截取加密字符串
        String realJsonData = jsonData.substring(4, Integer.valueOf(keyLen) + 4);
        PrivateKey privateKey = null;
        String desKeyBase64 = "";
        if (ShareParamConstant.EBUS_CER_MSG.equals(key)) {
            desKeyBase64 = rsaCerPlus.doDecrypt(realJsonData);
        } else {
            desKeyBase64 = rsaCerPlus.doDecryptNormally(realJsonData);
        }
        byte[] desKey = Base64Converter.decode(desKeyBase64.getBytes("UTF-8"));
        if ("3".equals(algorFlag)) {
            return RSACerPlus.decrypt(jsonData.substring(Integer.valueOf(keyLen).intValue() + 4), new String(desKey, "UTF-8"));
        }
        // base64解码
        byte msgBytesEnc[] = Base64Converter.decode(jsonData.substring(Integer.valueOf(keyLen) + 4).getBytes("UTF-8"));
        // des解密
        DesUtil des = DesUtil.getInstance();
        byte[] msgBytesBase64 = des.decrypt(msgBytesEnc, desKey, null);
        byte[] msgBytes = Base64Converter.decode(msgBytesBase64);
        return new String(msgBytes, "UTF-8");
    }

    /**
     * 获取客户端证书
     *
     * @param reqId
     * @param key
     * @return
     * @throws Exception
     */
    public static RSACerPlus genRSACerPlus(String bankId, String reqId, String key, String transChannelId) throws Exception {
        RSACerPlus rsaCerPlus = null;
        //获取客户端密钥,證書路徑
        if (StringUtil.isEmptyOrNull(bankId)) {
            bankId = AppParamConstant.DEFAULT_INSTID;
        }
        SrcChannelInfoMapper srcChannelInfoMapper = new SrcChannelInfoMapperImpl();
        SecPlanInfoMapper secPlanInfoMapper = new SecPlanInfoMapperImpl();
        CertInfoMapper certInfoMapper = new CertInfoMapperImpl();
        try {
            SrcChannelInfo srcChannelInfo = srcChannelInfoMapper.selectSrcChannelInfoByPrimaryKey(bankId, transChannelId, reqId);
            if (null != srcChannelInfo) {
                if (null != srcChannelInfo.getTransChannelStatus() && AppParamConstant.YES.equals(srcChannelInfo.getTransChannelStatus())) {
                    SecPlanInfo secPlanInfo = secPlanInfoMapper.selectSecPlanInfoByPrimaryKey(bankId, srcChannelInfo.getSecPlanId(), "CE10");
                    if (null != secPlanInfo) {
                        if (null != secPlanInfo.getSecPlanStatus() && AppParamConstant.YES.equals(secPlanInfo.getSecPlanStatus())) {
                            //获取证书路径
                            CertInfo certInfo = certInfoMapper.selectCertInfoByPrimaryKey(bankId + srcChannelInfo.getSecPlanId() + "CE10");
                            if (null != certInfo && null != certInfo.getCertSavePath() && AppParamConstant.YES.equals(certInfo.getKeyStatus()) && null != certInfo.getCertValue()) {
                                rsaCerPlus = RSACerFactory.getInstance().init(key, certInfo.getCertSavePath(), certInfo.getCertValue());
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new BizException("加载证书失败");
        }
        return rsaCerPlus;
    }
}
